package com.y.simple.service.impl;

import com.y.simple.bean.LoginBean;
import com.y.simple.bean.LoginUserMsg;
import com.y.simple.dto.UserMainQueryDto;
import com.y.simple.entity.UserMain;
import com.y.simple.global.ResultException;
import com.y.simple.service.IDictTermService;
import com.y.simple.service.IUserMainService;
import com.y.simple.service.IUserService;
import com.y.simple.utils.StringUtil;
import com.y.simple.utils.TokenUtil;
import com.y.simple.validator.UserValidator;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;


/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author y2014188432
 * @since 2023-05-13
 */
@Service
public class UserServiceImpl implements IUserService {

    @Resource
    private IUserMainService userMainService;

    @Resource
    private IDictTermService dictTermService;

    @Override
    public String login(LoginBean dto) {
        // 对入参进行校验
        UserValidator.loginValidator(dto);
        // 查询数据库
        UserMain entity = userMainService.getOne(dto.loginWrapper());
        // 判断
        if (entity == null) {
            throw new ResultException("400","账号或密码错误，请重新检查");
        }
        // 生成 token
        return createToken(entity);
    }

    public String createToken(UserMain entity) {
        LoginUserMsg loginUserMsg = new LoginUserMsg();
        loginUserMsg.setId(entity.getId());
        loginUserMsg.setType(entity.getUserType());
        // 查询权限
        loginUserMsg.setPower(dictTermService.analysisPowerCode(entity.getUserPower()));
        return TokenUtil.createToken(loginUserMsg);
    }


}
